package com.example.mall_system.service;

import com.example.mall_system.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    
    @Autowired
    private UserService userService;
    
    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        User user = userService.findById(Long.parseLong(userId));
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }
        
        // 根据用户角色构建权限
        String role;
        if (user.isAdmin()) {
            role = "ROLE_ADMIN";
        } else if (user.isSeller()) {
            role = "ROLE_SELLER";
        } else {
            role = "ROLE_BUYER";
        }
        
        return new org.springframework.security.core.userdetails.User(
            user.getId().toString(),
            user.getPassword(),
            Collections.singletonList(new SimpleGrantedAuthority(role))
        );
    }
}